DR. AJAY KUMAR PATHAK
ASSISTANT PROFESSOR
READ ALL THE NOTES CHAPTER WISE OF NUMERICAL ANALYSIS & PROGRAMMING IN C FOR B. Sc. Mathematics SEM 6 F.Y.U.G.P.
Copyright © by Dr. Ajay kumar pathak
B. Sc. Maths SEMESTER 6 NOTES BASED ON NEP
SUBJECT : MJ–15 (Th): NUMERICAL ANALYSIS & PROGRAMMING IN C
(To be selected by the students from)
Course Learning and Outcomes:- Know about the logics and algorithms needed for computer programming
UNIT 3:- Programmer’s model of a computer, Algorithms, Flow Charts, Data Types, Arithmetic and input /output instruction, Decision
control, Structures, Decision statements.
UNIT 4:- Logical and conditional operators Loop, Case control structures, Function, Recursions, Preprocessors, Arrays , Puppeting of string , Structures, Pointers, File Formatting.
NOTES OF
UNIT 3 FROM HERE :-
NOTES OF UNIT 3 OF C PROGRAMMING
What is Language in computer:- A computer language is
a formal set of instructions used to communicate with computers, enabling the
creation of software and applications. A computer language is a formal system
of coded commands, syntax, and rules used by humans to communicate instructions
to a computer.
Explanation
:- A computer language is a formal set of instructions that can be used to
produce various kinds of output, including software applications, scripts, or
algorithms. These languages are designed to communicate with computers and
allow programmers to write code that the computer can understand and execute.
These
are computer languages:-
(1) Machine level
language
(2) Assembly level
language
(3) High-level language
(4) 4th GL
(1) Machine level
language:- Machine level language is lowest level of
programming language. It handles binary data i.e. 0s and 1s. It directly
interacts with system. Machine language is difficult for human beings to
understand as it comprises combination of 0s and 1s. There is software which
translate programs into machine level language. Examples include operating
systems like Linux, UNIX, Windows, etc. In this language, there is no need of
compilers and interpreters for conversion and hence the time consumption is
less. However, it is not portable and non-readable to humans.
Example:-
00000001 00000010, 00000111 etc.
Examples
of Machine-Level Instructions:
Addition:
01100110 00001010.
Data
Transfer (Move/Load): 10110000 00000101 (e.g., move value to a register).
Memory/Control:
A series of bits like 1011000110001.
(2) Assembly level language:- Assembly language is a middle-level language. It consists of a set of instructions in a specific format called commands. It uses symbols to represent field of instructions. It is very close to machine level language. The computer should have assembler to translate assembly level program to machine level program. Examples include PASCAL, etc. It is in human-readable format and takes lesser time to write a program and debug it. However, it is a machine dependent language.
Example:-
|
Assembly Language |
Machine Code |
|
SUB AX, BX |
0010101110000011 |
|
MOV CX, AX |
100010111001000 |
|
MOV DX, 0 |
10111010000000000000000 |
Basic
Instruction Examples (x86 Assembly, Intel Syntax)
Below
are some fundamental assembly language instructions using the popular x86
assembly language syntax:
MOV
AL, 10: This instruction moves the immediate value 10 into the AL register (a
part of the accumulator register used for 8-bit data).
ADD
AH, BH: This command adds the content of the BH register to the content of the
AH register and stores the result in AH.
MOV
EAX, [EBX]: This moves the 4 bytes of data in memory at the address contained
in the EBX register into the EAX register.
JMP
label: This changes the program's flow of execution by jumping to a different
location in the code identified by the symbolic name label.
INC
COUNT: This increments the value stored in the memory variable COUNT by one.
(3) High-level language:-
High-level language uses format or language that is most familiar to users. The
instructions in this language are called codes or scripts. The computer needs a
compiler and interpreter to convert high-level language program to machine
level language. Examples include C++, Python, Java, etc. It is easy to write a
program using high level language and is less time-consuming. Debugging is also
easy and is a human-readable language. Main disadvantages of this are that it
takes lot of time for execution and occupies more space when compared to
Assembly- or Machine-level languages.
Following
is a simple example for a high level language:-
if
age < 18 {
printf("You are not eligible to
vote");
}
else{
printf("You are eligible to
vote");
}
Example:
- Python, Java, JavaScript, C++ etc
(4) 4th GL:-
A Fourth Generation Programming Language (4GL) is designed to make coding
easier and faster for people by using more human-friendly commands, compared to
older programming languages. In this article, we are going to discuss
fourth-generation programming language in detail.
These
languages are usually designed for specific purposes and are commonly used in
database programming and scripts such as PHP, Python, SQL, and many more. 4GLs
make programming easier, more efficient, and more effective for users with less
programming skills. 4th generation language is also known as a domain-specific
language or a high-productivity language.
Example:-
SQL, Python, Perl, MATLAB ((Matrix Laboratory etc.
PROGRAMS MODEL OF A COMPUTER :-
Program
Model of a Computer is a logical structure that shows how a program written in
C language takes input, processes it using instructions, and produces output
through the computer system.
The
Program Model of a Computer refers to the conceptual way in which a computer
understands, stores, and executes a program written in a programming language
such as C. It explains how instructions written by a programmer are converted
into actions performed by the computer system. In C language, the program model
helps us understand how a program is structured, how data flows inside the
program, how memory is used, and how the CPU executes instructions step by step
to produce the required output. In simple words, the program model describes
the relationship between input, processing, and output in a computer program.
When
a programmer writes a program in C language, the program does not directly
interact with the hardware. Instead, the program follows a logical model that
the computer system understands. This model includes the input of data, the
processing of that data using instructions, and the generation of output. The
program model of a computer in C language is therefore a bridge between human
thinking and machine execution. It shows how a real-world problem is converted
into a set of instructions that the computer can execute.
In
C language, the program model is closely related to the IPO concept, which
stands for Input, Process, and Output. Input refers to the data given to the
program by the user through devices such as the keyboard or through files.
Processing refers to the execution of logical and arithmetic operations on the
input data by the CPU according to the instructions written in the C program.
Output refers to the final result produced by the program and displayed on the
screen or stored in a file. Every C program, whether simple or complex, follows
this basic program model.
To
understand the program model more clearly, consider how a computer executes a C
program. First, the program is written using C language syntax. Then the C
compiler translates this high-level program into machine code, which is
understandable by the computer. After compilation, the program is loaded into
the main memory. The CPU then starts executing the program from the main()
function. Each instruction is fetched from memory, decoded, and executed by the
CPU. During execution, input is taken, data is processed, and output is
produced. This complete flow represents the
program model of a computer in C language.
A
simple example of the program model can be explained using a C program that
adds two numbers. In this program, the user enters two numbers as input. The
program processes the input by adding the two numbers. Finally, the program
displays the sum as output. This program clearly shows how the program model
works in C language.
Basic Block Diagram of
Program Model:-
Input → Processing (CPU) →
Output
↑
Memory
Explanation:- Input: Data entered by user (keyboard, mouse,
file),
Processing:- Instructions executed by CPU,
Memory:- Stores
program, data, and results, Output: Result shown on screen, printer, etc.
Program Model of Computer in C Language:- In C, every program follows a fixed structure. This
structure is the program model. General Structure of a C Program.
#include <stdio.h>
int main()
{
// Declaration
// Input
// Processing
// Output
return 0;
}
Explanation :- What is header file #include<stdio.h> ?
*The
C programming language provides many standard library functions for file input
and output. These functions make up the bulk of the C standard library header
<stdio.h>. stdio.h is a header file which has the necessary information
to include the input/output related functions in our program. Example printf,
scanf etc.
If
we want to use printf or scanf function in our program, we should include the
stdio.h header file in our source code.
Otherwise,
our program doesn’t know what is the definition of printf or scanf and it will
throw error/warning saying that implicit declaration of built-in function
‘printf’
Why #include ?:- #include
is a preprocessor directory.
It
will include the file which is given within the angle brackets
"<>" into the current source file.
Example:-
If we use #include<stdio.h> in your c program, it will include stdio.h
file into our source program which has the information for all input, output
related functions.
Why int main()?:- As we discussed earlier, the main
function is the starting point of program execution.
Operating
system (OS) initiates the program execution by invoking the main function.
And
it will expect an integer value from the main function. That integer value
represents the status of the program. That's why we declared main function
return type as int.
If
any error in the program while execution, the main function will return some
non-zero value to the operating system.
If
the program executed successfully without any error, It will return zero.
Why '{' ?:- C is the block structured programming
language where statements are grouped
together to achieve specific task using curly braces.
Open
curly brace { represents the starting point of the block.
Printf(“Hello World”);
printf
is a function which is defined in stdio.h header file. It will print everything
to the screen which is given inside the double quotes.
In
this case, Hello World will be printed as an output.
semicolon
";"
Every
statement in C should end with semicolon ;.
Why return 0;?:-
As
we declared main function return type as an integer, the calling function
(operating system) will expect an integer value from the main function. In main
function, we always explicitly return 0.
Program
execution will reach return 0 statement if and only if all the above statements
are executed without any error. If program execution reaches return 0
statement, We can ensure that there is no error in our program.
If
some error occurred while program execution, the main function will return some
non-zero value to the operating system to indicate the error.
Semicolon; indicates the end of the statement.
Why '}' ? :-
Close
curly brace indicates the end of the block.
In
other words, it indicates the end of main function.
COMPLETE EXAMPLE OF PROGRAM MODEL IN C:-
Example: Add Two Numbers:-
#include <stdio.h>
int main()
{
int a, b, sum;
printf("Enter two numbers: ");
scanf("%d
%d", &a, &b);
sum = a + b;
printf("Sum
= %d", sum);
return 0;
}
TYPES OF PROGRAM MODELS (VERY IMPORTANT):-
TYPE 1: Input–Process–Output (IPO) Model
Definition:- IPO model is a basic program model where data
is taken as input, processed, and output is generated.
Input → Process → Output
EXAMPLE:-
#include <stdio.h>
int main()
{
int x, y, result;
printf("Enter two numbers: ");
scanf("%d
%d", &x, &y);
result = x * y;
printf("Result = %d", result);
return 0;
}
TYPE 2: PROCEDURAL PROGRAM MODEL:-
Definition:- In Procedural Model, a program is divided into
functions (procedures). C language follows Procedural Programming Model.
Example in C (Procedural Model):-
#include <stdio.h>
void add()
{
int a, b;
printf("Enter two numbers: ");
scanf("%d
%d", &a, &b);
printf("Sum
= %d", a + b);
}
int main()
{
add();
return 0;
}
TYPE 3: MODULAR PROGRAM MODEL:-
Definition:- Modular Program Model divides a program into
independent modules.
Example in C (Modular Program):-
#include <stdio.h>
int add(int x, int y)
{
return x + y;
}
int main()
{
int a, b, result;
printf("Enter two numbers: ");
scanf("%d
%d", &a, &b);
result = add(a,
b);
printf("Sum
= %d", result);
return 0;
}
ALGORITHMS:- The word “algorithm” relates to the name of
the mathematician Al- khowarizmi, which means a procedure or a technique.
Algorithms
are step-by-step procedures for solving problems. They're crucial in
programming because they make programs faster and more efficient. They help solve
complex problems. They allow software to handle more data. They help to find
the best solutions in various fields.
They
form the foundation of writing a program. If it is written in English-like
sentences then, it is called PSEUDO CODE. It is a formula or a set of steps
that solves a particular problem for a specified problem. Each step in the
algorithm must be specified clearly.
A
programming algorithm is a process or formula for solving a problem. It
involves a sequence of specified actions that describe how to perform a task,
which the computer executes regularly. An algorithm follows a procedure
consisting of inputs and produces a result, known as the output.
Algorithm has the following characteristics:-
(1) Input:- The
first step involves defining the inputs that the algorithm will use. Inputs are
the data on which the algorithm will operate. It could be anything from a
single value to a complex data structure.
(2) Processing:- This is the core phase where
the algorithm performs operations on the inputs using a series of computational
steps. This phase is guided by logical and arithmetic calculations to process
the data effectively. Within the processing phase, there are often crucial
substeps:
(a) Decision making:- At various points
during processing, decisions need to be made based on certain conditions. This
substep involves directing the flow of the algorithm based on conditional
statements, leading to different paths in the algorithm.
(b) Looping:- For many algorithms, certain
steps need to be repeated multiple times until a specific condition is met.
Looping allows the algorithm to execute the same steps repeatedly, optimizing
the process and saving time.
(3) Output:- After processing the inputs through
various computational and conditional steps, the algorithm produces an output.
This output is the result of the algorithm’s operations and is used to solve
the problem or perform the task at hand.
(4) Termination:- An algorithm must have a defined
stopping point to ensure it doesn’t run indefinitely. Once all the steps are
executed successfully, and the output is produced, the algorithm reaches its
termination point.
Examples for understanding the concept of Algorithms:-
Example 1: Telling A Friend How To Boil Water In A Kettle.
Let’s
look at the 3 requirements for writing an algorithm for this task:
1. Input
– Kettle, Water
2. Tasks
to be preformed – Boiling water, fill up the kettle
3. Output
expected – Boiled water
Let’s give the instructions to a Friend:-
Step
1: Fill the kettle with water.
Step
2: Place it on the stove and turn on the burner.
Step
3: Turn off the burner when the water starts boiling.
Step
4: Stop.
Step
1: Put the kettle under the tap.
Step
2: Turn on the tap.
Step
3: Check if 90% of the kettle is filled.
Step
4: If not, repeat the above step.
Step
5: Turn off the tap.
Step
6: Place the kettle in the burner.
Step
7: Turn on the burner.
Step
8: Check if the water is 100 C
Step
9: If not, repeat the above step.
Step
10: Turn off the burner.
Step
11: Stop
EXAMPLE 2:-
Algorithm to Add Two Numbers
Algorithm:
ADD_TWO_NUMBERS
Start
Step
1 Read number A
Step
2 Read number B
Step
3 Calculate SUM = A + B
Step
4 Display SUM
Step
5 Stop
EXAMPLE 3:- Example of Algorithm Using Loop, Algorithm to Print Numbers from 1 to 5
Algorithm:
PRINT_NUMBERS
1. Start
2. Set
i = 1
·
While i ≤ 5, do
·
Print i
3. Increment
i = i + 1
4. Stop
EXAMPLE 4:- Algorithm to
Find Sum of First N Natural Numbers
Algorithm: SUM_N_NUMBERS
1. Start
2. Read
N
3. Set
SUM = 0
4. Set
i = 1
5. While
i ≤ N,
do
·
SUM = SUM + i
·
i = i + 1
6.
Display SUM
7. Stop
EXAMPLE 5:- Algorithm, Find
the largest number among three numbers
Step
1: Start
Step
2: Declare variables a,b and c.
Step
3: Read variables a,b and c.
Step
4: if a > b
if a > c
Display a is the largest number.
else
Display c is the largest number.
else
if b > c
Display b is the largest number.
else
Display c is the greatest
number.
Step
5: Stop
EXAMPLE 6:- Algorithm, Find
Roots of a Quadratic Equation ax2 + bx + c = 0
Step
1: Start
Step
2: Declare variables a, b, c, D, r1, r2, rp, ip, j;
Step
3: Read values a, b and c.
Step
4: Calculate discriminant
D ← b2 - 4ac
Step
5: If D ≥ 0
r1 ← (-b+√D)/(2a)
r2 ← (-b-√D)/(2a)
Display r1 and r2 as roots.
Else
j ← √(-1)
Calculate real part and imaginary
part
rp ← -b/(2a)
ip ← √(-D)/(2a)
Display rp+j(ip) and rp-j(ip) as
roots
Step
6: Stop
EXAMPLE 7:- Algorithm,
Find the factorial of a number
Step
1: Start
Step
2: Declare variables n, factorial and i.
Step
3: Initialize variables
factorial ← 1
i ← 1
Step
4: Read value of n
Step
5: Repeat the steps until i = n
5.1: factorial ← factorial*i
5.2: i ← i+1
Step
6: Display factorial
Step
7: Stop
EXAMPLE 8:- Algorithm, Find
the Fibonacci series till the term less than 1000
Step
1: Start
Step
2: Declare variables first_term,second_term and temp.
Step
3: Initialize variables first_term ← 0 second_term ← 1
Step
4: Display first_term and second_term
Step
5: Repeat the steps until second_term ≤ 1000
5.1: temp ← second_term
5.2: second_term ← second_term +
first_term
5.3: first_term ← temp
5.4: Display second_term
Step
6: Stop
EXAMPLE 9: -Algorithm: print numbers from 1 to 10.
1. Start
2. Now
initialize c = 1
3. Now
we check the condition if c < 11, then go to
step 4 otherwise go to step 6.
4. Print
c
5. c = c + 1 then go to step 3
6. Stop
Types of Algorithms:-
(1) Search algorithms:- Designed to
retrieve information stored within some data structure, e.g., binary search
algorithm used to find a particular item in a sorted list.
(2)
Sorting algorithms:- They rearrange the elements of a dataset in a specified
order, like quicksort and mergesort, which are efficient for sorting large
datasets.
(3)
Graph algorithms:- These deal with graphs, which are mathematical structures
used to represent pairwise relations between objects, e.g. Dijkstra's algorithm finds the shortest path
between nodes in a graph.
ADVANTAGES OF ALGORITHM:-
(1)
Clarity and Precision:- Algorithms provide a clear and precise set of
instructions to solve a problem, making it easier to understand and implement.
(2)
Reusability:- Once an algorithm
is developed, it can be reused to solve similar problems without redesigning
the solution from scratch.
(3)
Efficiency:- Algorithms help in finding the most efficient way to solve a
problem, optimizing time and resource usage.
(4)
Automation:- Algorithms enable automation of tasks by providing step-by-step
instructions that can be executed by computers.
(5)
Debugging and Maintenance:- Algorithms
make it easier to identify errors and maintain the solution since the logic is
clearly defined.
(6)
Scalability:- Well-designed algorithms can handle larger inputs or more complex
problems by adapting the steps accordingly.
(7)
Communication:- Algorithms serve as a common language between programmers and
stakeholders to explain how a problem is solved.
(8)
Foundation for Programming:- Algorithms are the basis for writing computer
programs and developing software applications.
Disadvantages of Algorithms:-
1.
Algorithms is Time consuming.
2.
Difficult to show Branching and Looping in Algorithms.
3.
Big tasks are difficult to put in Algorithms.
HISTORY OF THE FLOW CHART :-
Industrial
engineers Frank and Lillian Gilbreth first introduced the concept of flowcharts
to the American Society of Mechanical Engineers (ASME) in 1921 with their Flow
Process Chart. Their presentation, entitled Process Charts: First Steps in
Finding the One Best Way to Do Work, laid the groundwork for the role of
flowcharts in workflow optimization.
Throughout
the 1930s and 1940s, other engineers further honed the concept of the flowchart
and improved its efficacy as a tool. In 1947, the ASME released a standardized
set of common flowchart symbols based on the Gilbreths’ original work.
The
1990s saw the arrival of Unified Modeling Language (UML) activity
diagrams—digital flowcharts created with specialized UML-based flowchart
software. UML was created in the 1990s to standardize common flowchart symbols.
FLOW CHAT:-
A
flow chart is a graphical or symbolic representation of a process. These visual
tools, also known as flow diagrams. Each step in the process is represented by
a different symbol and contains a short description of the process step. The
flow chart symbols are linked together with arrows showing the process flow
direction. These flow charts are a near way to design and document each step in
a workflow and illustrate how they’re interconnected. Using a standardized set
of symbols, including shapes and arrows, flowcharts make it possible to show
complex processes with a shared visual language.
Flowchart Symbols:-
Different
flow chart symbols have different meanings. The most common flow chart symbols
are:
1. Terminator:
An oval flow chart shape indicating the start or end of the process.
2. Process:
A rectangular flow chart shape indicating a normal process flow step.
3. Decision:
A diamond flow chart shape indication a branch in the process flow.
4. Connector:
A small, labeled, circular flow chart shape used to indicate a jump in the
process flow. (Shown as the circle with the letter "A", below.)
5. Data:
A parallelogram that indicates data input or output (I/O) for a process.
6. Document:
Used to indicate a document or report (see image in sample flow chart below).
EXAMPLE 1:-
Draw a Flowchart to find the sum of 2 numbers which is already given , Where A=10, B=20
EXAMPLE 2:- Draw a Flowchart to INPUT tow numbers and find the sum of entered numbers.
EXAMPLE 3: Draw a Flowchart to find the greatest
number among the 2 numbers.
EXAMPLE 4:- Draw a Flowchart to check whether the
input number is odd or even
EXAMPLE 5: - Draw a Flowchart to print the input
number 5 times.
EXAMPLE 6:-
Draw a Flowchart to print numbers from 1 to 10.
EXAMPLE 7:-Draw a Flowchart to print the first 5
multiples of 3.
Types of Flowcharts:-
Flowcharts are:-
(1)
Process Flowchart:- This type of Flowchart shows all the activities that are
involved in making a product. It provides a pathway to analyze the product to
be built. It is most commonly used in process engineering to illustrate the
relation between the major as well as minor components present in the product.
It is used in business product modeling to help understand employees about the
project requirements and gain some insight into the project.
(2)
Data Flowchart:- It is used to analyze the data, specifically it helps in
analyzing the structural details related to the project. Using this Flowchart,
one can easily understand the data inflow and outflow from the system. It is
most commonly used to manage data or to analyze information to and fro from the
system.
(3)
Business Process Modeling Diagram:- Using this Flowchart or diagram, one
can analytically represent the business process and help simplify the concepts
needed to understand business activities and the flow of information. This
Flowchart illustrates the business process and models graphically which paves
the way for process improvement.
(4)
System Flowcharts: These “show the flow of data to and through the major
components of a system such as data entry, programs, storage media, processors,
and communication networks.”
Advantages of Flowchart:-
(1) Better Communication:- A flowchart is a
pictorial representation of a program. Therefore, it is easier for a programmer
to explain the logic of a program to some other programmer, or to his/her boss
through a flowchart rather than the program itself.
(2) Proper Program Documentation:- Program documentation involves collecting, organizing,
storing, and otherwise maintaining a complete historical record of programs,
and other documents associated with a system. Good documentation is needed for
the following reasons:-
(a)
Documented knowledge belongs to an organization, and does not disappear with
the departure of a programmer.
(b)
If a project is postpones, documented work helps in restarting the project
later from the stage at which it was stopped.
(c
). If a programmer has to modify a program, documented work provides him/her a
more understandable record of what was originally done.
(3) Efficient coding:- Once a flowchart is ready, programmers find it
very easy to write the corresponding program because the flowchart acts as a
road map for them. It guides them to go from the starting point of the program
to the final point, ensuring that no steps are omitted. The ultimate result is
an error free program developed at a faster rate.
(4) Systematic Debugging:- A flowchart is very helpful in detecting,
locating, and removing mistakes in a program in a systematic manner because
programmer find it easier to follow the logic of the program in flowchart form.
The process of removing errors in a program is known as debugging.
(5) Systematic Testing: Testing is the
process of confirming whether a program will successfully do all its proposed
jobs under the specified constraints. For testing a program, the program is
executed with different sets of data as input to test the different paths in
the program logic.
Disadvantages of Flowchart:-
(1) Flowcharts are very time consuming and
laborious to draw with proper symbols and spacing, especially for large complex
programs.
(2) Owing to the symbol-string nature of
flowcharting, any change or modification in the program logic will usually
require a completely new flowchart. Redrawing a flowchart being a tedious task,
many programmers do not redraw or modify the corresponding flowcharts when they
modify their programs. This leaves a program and its flowchart in an
inconsistent state. That is, the logic used in the program and that shown in
its flowchart do not match. This downfalls the purpose of use of flowcharts as
documentation support for programs.
(3)
There are no standards determining the amount of detail that should be included
in a flowchart.
(4) Manual tracing is needed to check
correctness of flowchart drawn on paper.
(5) Showing many branches and looping in
flowchart is difficult.
(6) In case of complex program/algorithm,
flowchart becomes very complex and clumsy.
Modification of flowchart is sometimes time consuming.
DATA TYPES:-
A
data type in C refers to the type of data used to store the information. Data types in C refer to a wide system used
for declaring variables or functions of different types. The type of a variable
determines how much space it occupies in storage and how the bit pattern stored
is interpreted.
C program data types are classified into three main categories:-
(1) Basic Data Types (2) Derived Data Types (3) User-Defined Data
Types
1. Basic Data Types:- These include
fundamental types like int (for integers), char (for characters), float (for
floating-point numbers), and double (for double-precision floating-point
numbers).
(i)
int :- Used to store integer values, which are whole numbers without a decimal
point. Generally occupies 2 or 4 bytes, depending on the system.
Excample
:-
#include
<stdio.h>
int
main(void)
{
int age = 25;
printf("%d", age);
return 0;
}
(ii)
char:- Used to store single characters. Characters are enclosed in single
quotes ('A'). Occupies 1 byte of memory.
#include
<stdio.h>
int
main(void)
{
char grade = 'A';
printf("%c", grade);
return 0;
}
(iii)
float : -Used to store floating-point numbers (numbers with decimals).Generally
occupies 4 bytes of memory.
Example:
- #include
<stdio.h>
int
main(void)
{
float temperature = 36.6f;
printf("%.1f", temperature);
return 0;
}
(iv)
double :- Used to store double-precision floating-point numbers, offering more
precision than float. Generally occupies 8 bytes of memory.
Example:-
#include
<stdio.h>
int
main(void)
{
double pi = 3.14159265359;
printf("%.10lf", pi);
return 0;
}
(2). Derived Data Types:- These are derived from basic data types and include arrays, pointers, and functions.
Examples:-
(i) Arrays:- An array is a collection of elements
of the same data type, stored in contiguous memory locations.
Example:-
#include <stdio.h>
int
main(void)
{
int numbers[5] = {1, 2, 3, 4, 5};
printf("%d", numbers[0]);
return 0;
}
(ii)
Pointers:- A pointer stores the memory
address of another variable.
Example:-
#include <stdio.h>
int
main(void) {
int x = 10;
int *ptr = &x;
printf("%d", *ptr);
return 0;
}
(iii)
Functions:- A function is a block of code that performs a specific task and can
return a value.
Example:-
#include
<stdio.h>
int
add(int a, int b)
{
return a + b;
}
int
main(void)
{
printf("%d", add(3, 5));
return 0;
}
(3). User-Defined Data Types: These are created by
the programmer and include structures (struct), unions (union), and
enumerations (enum). The user-defined types in C language provide flexibility
and enhance readability, especially when dealing with more complex data.
(i)
Structures (struct):- A structure is a user-defined data type that groups
variables of different types under a single name.
Example:-
#include <stdio.h>
struct
Student {
int id;
char name[50];
float grade;
};
int
main(void) {
struct Student s1 = {1, "Ajay",
95.5f};
printf("ID: %d, Name: %s, Grade:
%.1f\n", s1.id, s1.name, s1.grade);
return 0;
}
(ii)
Unions (union):- A union is similar to a structure, but members share the same
memory location, meaning only one member can hold a value at a time.
Example:-
#include <stdio.h>
union
Data {
int i;
float f;
};
int
main(void) {
union Data data;
data.i = 10;
printf("i: %d\n", data.i);
data.f = 20.5f;
printf("f: %.2f\n", data.f);
return 0;
}
(iii)
Enumerations (enum):- An enum is a data type consisting of named integer
constants, improving code readability for sets of values.
Example:-
#include
<stdio.h>
enum
Days { Sunday, Monday, Tuesday };
int
main(void) {
enum Days today = Monday;
printf("Today is: %d\n", today);
return 0;
}
Data Type Modifiers in C:-
(1). signed:- By default, integer types are signed,
meaning they can store both positive and negative values.
Example:- signed int num = -10; // Stores both positive
and negative numbers.
(2). unsigned:- An unsigned variable can only hold
non-negative values, allowing a larger positive range.
Example:-
unsigned int num = 300; // Stores only positive values.
(3) . short:- The short modifier reduces the size of
an integer to save memory, typically 2 bytes.
Example:-
short int num = 1000;
(4) . long:- The long modifier increases the size of
a data type, typically 4 or 8 bytes.
Example:-
long
int bigNumber = 1000000;
Data Types in C With Size and Range:-
Different
data types in C consume varying amounts of memory. For example, an int uses 2
or 4 bytes, a char uses 1 byte, a float uses 4 bytes, and a double uses 8
bytes. The size of these data types can vary depending on the system
architecture (32-bit vs. 64-bit).
The
table below shows the data types in C and their size along with range:-
|
Data Type |
Memory Size |
Signed Range |
Unsigned Range |
|
char |
1 byte |
-128 to 127 |
0 to 255 |
|
short |
2 bytes |
-32,768 to 32,767 |
0 to 65,535 |
|
int |
4 bytes |
-2,147,483,648 to 2,147,483,647 |
0 to 4,294,967,295 |
|
long |
4 bytes |
-2,147,483,648 to 2,147,483,647 |
0 to 4,294,967,295 |
|
float |
4 bytes |
3.4E-38 to 3.4E+38 |
N/A |
|
double |
8 bytes |
1.7E-308 to 1.7E+308 |
N/A |
|
Data Type |
Format Specifier |
Minimal Range |
Typical Bit Size |
|
unsigned char |
%c |
0 to 255 |
8 |
|
char |
%c |
-127 to 127 |
8 |
|
signed char |
%c |
-127 to 127 |
8 |
|
int |
%d, %i |
-32,767 to 32,767 |
16 or 32 |
|
unsigned int |
%u |
0 to 65,535 |
16 or 32 |
|
signed int |
%d, %i |
Same as int |
Same as int 16 or 32 |
|
short int |
%hd |
-32,767 to 32,767 |
16 |
|
unsigned short int |
%hu |
0 to 65,535 |
16 |
|
signed short int |
%hd |
Same as short int |
16 |
|
long int |
%ld, %li |
-2,147,483,647 to 2,147,483,647 |
32 |
|
long long int |
%lld, %lli |
-(263 – 1) to 263 – 1 (It will be
added by the C99 standard) |
64 |
|
signed long int |
%ld, %li |
Same as long int |
32 |
|
unsigned long int |
%lu |
0 to 4,294,967,295 |
32 |
|
unsigned long long int |
%llu |
264 – 1 (It will be added by the C99
standard) |
64 |
|
float |
%f |
1E-37 to 1E+37 along with six digits
of the precisions here |
32 |
|
double |
%lf |
1E-37 to 1E+37 along with six digits
of the precisions here |
64 |
|
long double |
%Lf |
1E-37 to 1E+37 along with six digits
of the precisions here |
80 |
ARITHMETIC AND INPUT / OUTPUT
INSTRUCTIONS :-
Arithmetic
instructions use operators to perform mathematical calculations on data, while
input/output (I/O) instructions use library functions to manage data flow
between the program and external devices like the keyboard and screen.
Arithmetic
Instructions, Arithmetic instructions utilize specific operators to perform
calculations on numeric data (integers and floating-point numbers).
Like:-
Common I/O Functions :- printf(): This function sends formatted output to the
standard output device (usually the console/screen). It uses format specifiers
(e.g., %d for integer, %f for float, %c for character) to display variables and
text.
Example:
printf("The sum is: %d\n", sum);
Like:-
scanf(): This function reads formatted input from the standard input device
(usually the keyboard). It requires the address-of operator (&) before the
variable name to store the input value at the correct memory location.
Example:
scanf("%d", &a);
Like:-
Other I/O Functions:- getchar()/putchar(): Used for inputting and outputting a
single character at a time. gets()/puts(): Used for inputting and outputting
strings. (Note: gets() is deprecated due to potential security issues; fgets()
is a safer alternative).
Example
#include
<stdio.h>
int
main() {
int age;
printf("Enter your age: "); //
Output instruction
scanf("%d", &age); // Input instruction
printf("You entered: %d\n", age);
// Output instruction
return 0;
}
NOW NOTES FROM HERE ON ARITHMETIC AND INPUT / OUTPUT INSTRUCTIONS:-
TYPES OF OPERATORS :-
C
divides the operators into the following groups:
(1) ARITHMETIC OPERATORS
(2) ASSIGNMENT OPERATORS
(3) COMPARISON OPERATORS
(4) LOGICAL OPERATORS
(5) BITWISE OPERATORS (ADVANCED)
ARITHMETIC OPERATORS :- Arithmetic operators in
C are fundamental components that enable developers to perform basic arithmetic
/ mathematical calculations within C programs. These operators include addition
(+), subtraction (-), multiplication (*), division (/), and modulus (%).
In
other words, these operators are used to manipulate numeric data types, such as
integers and floating-point numbers, allowing us to perform tasks like
addition, subtraction, multiplication, division, and finding remainders.
These
can be classified into two types based on the number of operands they work on:-
(1) Binary Arithmetic
Operators
(2) Unary Arithmetic
Operators
(1) Binary Operators In
C:- The
term binary operators can be used in two contexts, one in general programming
and the other in binary arithmetic. In the context of binary arithmetic, a
binary operator can used to perform operations on binary data only.
But
in general programming, a binary operator is one that takes two operands and
performs the respective calculations on their values. The table below lists the
binary arithmetic operators in C, with a brief description, and an example of
arithmetic calculations.
|
Operator |
Name of the Operator |
Arithmetic Operation |
Syntax |
|
+ |
Addition |
It calculates the sum of two operands. |
A + B |
|
– |
Subtraction |
It subtracts the second operand from
the first operand. |
A – B |
|
* |
Multiplication |
It calculates the product of or
multiplies the two operands. |
A * B |
|
/ |
Division |
It divides the first operand by the
second operand. |
A / B |
|
% |
Modulus |
It calculates the remainder when the
first operand is divided by the second operand. |
A % B |
EXAMPLE OF BINARY ARITHMETIC OPERATORS WITH PROGRAM
#include
<stdio.h>
int
main()
{
int a = 50, b = 40, result;
// Addition
res = a + b;
printf("a + b is %d\n", result);
// Subtraction
res = a - b;
printf("a - b is %d\n", result);
// Multiplication
res = a * b;
printf("a * b is %d\n", result);
// Division
res = a / b;
printf("a / b is %d\n", result);
// Modulus
res = a % b;
printf("a %% b is %d\n", result);
return 0;
}
(2) Unary Arithmetic Operators:- The unary arithmetic operators work with a single operand. In C, we have four such operators which are as follows:-
|
Name |
Operator |
Description |
Syntax |
|
- - |
Decreases the integer value of the
variable by one. |
- -a or a- - |
|
|
+ + |
Increases the integer value of the
variable by one. |
+ +a or a+ + |
|
|
+ |
Returns the value of its operand. |
+a |
|
|
- |
Returns the negative of the value of
its operand. |
-a |
EXAMPLE OF UNARY ARITHMETIC OPERATORS WITH PROGRAM
#include
<stdio.h>
int
main()
{
int a = 100, result;
// post-incrementing a result is assigned 100,
a is not updated yet
res = a++;
printf("a is %d, res is %d\n", a,
result);
// post-decrementing result is assigned 11,
a is not updated yet
res = a--;
printf("a is %d, result is %d\n",
a, result);
res = ++a;
// a and res have same values = 11
printf("a is %d, result is %d\n",
a, result);
res = -
-a;
// a and res have same values = 10
printf("a is %d, result is %d\n",
a, result);
printf("+a is %d\n", +a);
printf("-a is %d", -a);
return 0;
}
(2) ASSIGNMENT
OPERATORS:-
An
assignment operator is used for assigning a value to a variable. The most
common assignment operator is = .
Assignment
operators are used to assign value to a variable. The left side operand of the
assignment operator is a variable and the right side operand of the assignment
operator is a value. The value on the right side must be of the same data type
as the variable on the left side otherwise the compiler will raise an error.
|
Symbol |
Operator |
Description |
Syntax |
|
= |
Simple Assignment |
Assign the value of the right operand
to the left operand. |
a = b |
|
+= |
Plus and assign |
Add the right operand and left operand
and assign this value to the left operand. |
a += b |
|
-= |
Minus and assign |
Subtract the right operand and left
operand and assign this value to the left operand. |
a -= b |
|
*= |
Multiply and assign |
Multiply the right operand and left
operand and assign this value to the left operand. |
a *= b |
|
/= |
Divide and assign |
Divide the left operand with the right
operand and assign this value to the left operand. |
a /= b |
|
%= |
Modulus and assign |
Assign the remainder in the division
of left operand with the right operand to the left operand. |
a %= b |
|
&= |
AND and assign |
Performs bitwise AND and assigns this
value to the left operand. |
a &= b |
|
|= |
OR and assign |
Performs bitwise OR and assigns this
value to the left operand. |
a |= b |
|
^= |
XOR and assign |
Performs bitwise XOR and assigns this
value to the left operand. |
a ^= b |
|
>>= |
Rightshift and assign |
Performs bitwise Rightshift and assign
this value to the left operand. |
a >>= b |
|
<<= |
Leftshift and assign |
Performs bitwise Leftshift and assign
this value to the left operand. |
a <<= b |
EXAMPLE
:-
#include
<stdio.h>
int
main() {
int a = 25, b = 5;
// using operators and printing results
printf("a = b: %d\n", a = b);
printf("a += b: %d\n", a += b);
printf("a -= b: %d\n", a -= b);
printf("a *= b: %d\n", a *= b);
printf("a /= b: %d\n", a /= b);
printf("a %%= b: %d\n", a %= b);
printf("a &= b: %d\n", a
&= b);
printf("a |= b: %d\n", a |= b);
printf("a ^= b: %d\n", a ^= b);
printf("a >>= b: %d\n", a
>>= b);
printf("a <<= b: %d\n", a
<<= b);
return 0;
}
(3) COMPARISON OPERATORS
or RELATIONAL OPERATORS:-
Comparison
operators (Comparison Operators ka use do values ko compare karne ke liye hota
hai. Ye comparison ka result hamesha TRUE (1) ya FALSE (0) hota hai. Example:- kya
a aur b equal hain, kya a b se bada hai) or RELATIONAL OPERATORS (Relational Operators ka
use bhi do values ke beech relationship check karne ke liye hota hai, jaise greater
than, less than, equal to, Final
Conclusio, C programming me Comparison Operators aur
Relational Operators SAME hote hain. Sirf naam alag hai, kaam ek hi hai.)
Comparison operators or RELATIONAL OPERATORS are used to compare two values (or variables). This is important in programming, because it helps us to find answers and make decisions. Comparison Operators in programming are used to compare values and determine their relationship, such as equality, inequality, greater than, less than, etc. They evaluate expressions and return a Boolean value (true or false) based on the comparison result, crucial for decision-making in conditional statements and loops
A
list of all comparison operators:
|
Operator |
Name |
Example |
Description |
|
= = |
Equal to |
x = = y |
Returns 1 if the values are equal |
|
! = |
Not equal |
x != y |
Returns 1 if the values are not equal |
|
> |
Greater than |
x > y |
Returns 1 if the first value is
greater than the second value |
|
< |
Less than |
x < y |
Returns 1 if the first value is less
than the second value |
|
> = |
Greater than or equal to |
x >= y |
Returns 1 if the first value is
greater than, or equal to, the second value |
|
< = |
Less than or equal to |
x <= y |
Returns 1 if the first value is less
than, or equal to, the second value |
//
Working of relational operators OR Comparison operators
#include
<stdio.h>
int
main()
{
int a = 5, b = 5, c = 10;
printf("%d == %d is %d \n", a, b,
a = = b);
printf("%d == %d is %d \n", a, c,
a = = c);
printf("%d > %d is %d \n", a,
b, a > b);
printf("%d > %d is %d \n", a,
c, a > c);
printf("%d < %d is %d \n", a,
b, a < b);
printf("%d < %d is %d \n", a,
c, a < c);
printf("%d != %d is %d \n", a, b,
a ! = b);
printf("%d != %d is %d \n", a, c,
a ! = c);
printf("%d >= %d is %d \n", a,
b, a > = b);
printf("%d >= %d is %d \n", a,
c, a > = c);
printf("%d <= %d is %d \n", a,
b, a < = b);
printf("%d <= %d is %d \n", a,
c, a < = c);
return 0;
}
(4) LOGICAL OPERATORS:-
Logical
operators in C are used to perform logical operations on given expressions.
These operators evaluate the expressions based on the values and return a
boolean value as a result. They play a critical role in decision-making
processes within a program by allowing the program to decide the direction to
take based on certain conditions. Being proficient in the use of logical
operators means you can write more efficient and effective C programs.
EXAMPLE:-
|
Symbol |
Operator |
Description |
Syntax |
|
&& |
Logical AND |
Returns true if both the operands are true. |
a && b |
|
|| |
Logical OR |
Returns true if both or any of the
operand is true. |
a || b |
|
! |
Logical NOT |
Returns true if the operand is false. |
!a |
EXAMPLE:
#include
<stdio.h>
int
main() {
int a = 25, b = 5;
// using operators and printing results
printf("a && b : %d\n", a
&& b);
printf("a || b : %d\n", a || b);
printf("!a: %d\n", !a);
return 0;
}
OUTPUT
:-
a
&& b : 1
a
|| b : 1
!a:
0
(5) BITWISE OPERATORS (ADVANCED):-
The
Bitwise operators are used to perform bit-level operations on the operands. The
operators are first converted to bit-level and then the calculation is
performed on the operands.
Note:
Mathematical operations such as addition, subtraction, multiplication, etc. can
be performed at the bit level for faster processing.
|
Symbol |
Operator |
Description |
Syntax |
|
& |
Bitwise AND |
Performs bit-by-bit AND operation and
returns the result. |
a & b |
|
| |
Bitwise OR |
Performs bit-by-bit OR operation and
returns the result. |
a | b |
|
^ |
Bitwise XOR |
Performs bit-by-bit XOR operation and
returns the result. |
a ^ b |
|
~ |
Bitwise First Complement |
Flips all the set and unset bits on
the number. |
~a |
|
<< |
Bitwise Leftshift |
Shifts bits to the left by a given
number of positions; multiplies the number by 2 for each shift. |
a << b |
|
>> |
Bitwise Rightshift |
Shifts bits to the right by a given
number of positions; divides the number by 2 for each shift. |
a >> b |
EXAMPLE:-
#include
<stdio.h>
int
main() {
int a = 25, b = 5;
// using operators and printing results
printf("a & b: %d\n", a &
b);
printf("a | b: %d\n", a | b);
printf("a ^ b: %d\n", a ^ b);
printf("~a: %d\n", ~a);
printf("a >> b: %d\n", a
>> b);
printf("a << b: %d\n", a
<< b);
return 0;
}
OUTPUT:-
a
& b: 1
a
| b: 29
a
^ b: 28
~a:
-26
a
>> b: 0
a
<< b: 800
INPUT / OUTPUT INSTRUCTIONS :-
Input-output
operations in C are essential for interacting with users and handling data.
These operations allow a program to take input from the user or external files
and display results. C language provides libraries (header files) that contain
various functions for input and output.
In
C, there are many input and output for different situations, but the most
commonly used functions for Input / Output are scanf() and printf()
respectively. These functions are part of the standard input / output library
<stdio.h>. scanf() takes user inputs (typed using keyboard) and printf()
displays output on the console or screen.
Input in C:-
Input
in C programming means gathering data from the user or external sources for
processing. The most common way is through the console, where functions like
scanf() are used for formatted input.
Types of input statements / Function :-
(1) scanf() Function
(2) getchar() Function
(3) gets() Function
(1) scanf():-scanf()
is used to read user input from the console. It takes the format string and the
addresses of the variables where the input will be stored.
It
has the following form:-
scanf
(“format string”, &v1, &v2, . . . , &vn);
Where
v1, v2, . . . , vn are variables whose values are to be read from the keyboard.
“format
string” is the control string which represents the format specification. The
symbol & (ampersand) represents the memory address where the variable value
is to be stored.
Example 1:- Taking Input of Integer Value,
scanf(“%d%d”,
&a, &b); to read value of int variables a and b.
PROGRAM:-
#include
<stdio.h>
int
main()
{
//
with the use of scanf()
int
input_from_user;
printf(“Hello,
please enter a digit here: “);
scanf(“%d”, &input_from_user);
printf(“The
digit that you entered is: %d”, input_from_user);
return
0;
}
OUTPUT
Hello,
please enter a digit here: 25
The
digit that you entered is: 25
EXAMPLE 2:-
#include
<stdio.h>
int
main() {
//
with the use of scanf()
float
input_from_user;
printf(“Hi,
please enter a decimal value: “);
scanf(“%f”, &input_from_user);
printf(“The
value that you have entered is: %f”, input_from_user);
return
0;
}
OUTPUT:
Hi,
please enter a decimal value: 8.016
The
value that you have entered is: 8.016
EXAMPLE 3:- Taking Input of Character Value
#include
<stdio.h>
int
main() {
//
with the use of scanf()
char
gender;
printf(“Hi,
we would like you to enter your gender (F, M or O): “);
scanf(“%c”, &gender);
printf(“Thanks,
your gender is: %c”, gender);
return
0;
}
OUTPUT
Hi,
we would like you to enter your gender (F, M or O): F
Thanks,
your gender is: F
EXAMPLE 4:- Taking Input of Multiple Values
#include
<stdio.h>
#include<conio.h>
int
main() {
//
with the use of scanf() for multiple numbers of inputs
int
age;
char
gender;
printf(“Please
enter your gender and then age(F, M or O): “);
scanf(“%d
%c”, &gender, &age);
printf(“The
information that you entered is: %c and %d”, gender, age);
return
0;
}
OUTPUT
Please
enter your gender and then age(F, M or O): 24 M
The
information that you entered is: 24 M
(2) getchar() Function:-
Reads a single
character from the user.
The
getchar() function in a program basically reads the characters available from
the terminal. It then returns these characters in the form of integers. The
getchar() function is capable of reading just a single character at any given
time. A programmer can easily use this method in the case of a loop if they are
willing to read more than a single character.
Example:-
#include
<stdio.h>
#include
<string.h>
#include<conio.h>
void
main( )
{
int
x;
printf(“Please
enter a character here”);
/*
We
are taking a character in the form of input and storing it in the variable x
*/
x
= getchar();
/*
we
are displaying the character stored in the variable x
*/
putchar(x);
}
OUTPUT
Please
enter a character here: Chocolate C
(The
compilation of the code mentioned above will ask the programmer to enter their
desired value. Whenever we enter the available value, the program will generate
an output displaying the value that we have entered in the program. We will get
only C)
(3) gets() Function:-
The
gets() function in C language was once a popular method for reading strings
from user input. It allows you to capture entire lines, including spaces,
making it simpler than other input functions like scanf().The newline character
is then replaced by a null terminator, and the resulting string is stored in
str.
syntax
of the gets() function :- char *gets(char *str);
EXAMPLE 1:-
#include
<stdio.h>
#include
<string.h>
#include<conio.h>
int
main() {
char abc[100];
printf("Enter a string: ");
//
Taking input using gets()
gets(abc);
printf("You entered: %s", abc);
return 0;
}
OUTPUT
:- ajay kumar pathak
Explanation:
In this program, gets() reads a line of input from the user and stores it in
the array abc.
abc:
A pointer to the character array where the input string will be stored.
Return
Value:- Returns a pointer to the string (str) on success., Returns NULL if an
error occurs or if EOF is encountered before any characters are read.
OUTPUT INSTRUCTIONS:-
(1) printf( ) Function:- printf() function
is used to print/display values of variables using the standard output device
(monitor). The printf() function is used to print formatted output to the
standard output stdout (which is generally the console screen). It is one of
the most commonly used functions in C
It
has the following form printf (“format string”, v1, v2, . . . , vn);
Where
v1, v2, . . . , vn are variables whose values are to be display in the monitor.
“format string” is the control string which represents the format specification.
Example:
- printf
(“%f”, s);
printf
(“\n sum=%6.2f”, s);
EXAMPLE 1:-
#include
<stdio.h>
int
main() {
// Prints some text
printf("I AM A PRINT STATEMENT ");
return 0;
}
EXAMPLE 2: -
#include
<stdio.h>
int
main()
{
int
age = 15;
// Prints Age
printf("The value of the variable age
is = %d\n", age);
return 0;
}
OUTPUT:- The value of the variable age is = 15
EXAMPLE 3: - float and double Output
#include
<stdio.h>
#include
<string.h>
#include<conio.h>
int
main()
{
float number1 = 13.5;
double number2 = 12.4;
printf("number1 = %f\n",
number1);
printf("number2 = %lf", number2);
return 0;
}
(2) putchar() function:-
The
putchar() function in C is used to display a single character on the screen. It
takes one character as input and writes it to the standard output (console).
This function is simple to use and is commonly employed in programs where
character-by-character output is needed, such as printing patterns, handling
text, or debugging small portions of code.
Syntax:- Syntax
ch = getchar( ); where ch is a char Var.
Example:- When this function is executed, the
computer will wait for a key to be pressed and assigns the value to the variable
when the “enter” key pressed.
#include<stdio.h>
#include<conio.h>
#include
<string.h>
void
main()
{
char
ch;
printf("Enter
a char:- ");
ch=getchar(
);
printf("ch=%c",ch);
}
OUTPUT:- Enter a char M:- M
EXAMPLE 2:- Using getchar() and putchar() in C taking vales from the
user
#include
<stdio.h>
#include<conio.h>
int
main()
{
char ch;
printf("Enter a character: ");
ch = getchar(); // take one character from user
printf("You entered: ");
putchar(ch); // display the character
return 0;
}
EXAMPLE 3:- Using getchar() and putchar(), Read and Print
Multiple Characters (Until Enter is Pressed)
#include
<stdio.h>
int
main()
{
char ch;
printf("Enter text (press Enter to
stop):\n");
while ((ch = getchar()) != '\n')
{
putchar(ch);
}
return 0;
}
(3) puts() Function:- The puts() function in
C is used to display strings on the screen. It prints a given string and
automatically moves the cursor to the next line by adding a newline (\n) after
the output. This makes puts() simpler than printf() for basic string output because
you don’t need to include a newline manually. However, it is specifically
designed for printing strings and cannot handle variables like integers or
floats.
In
C programming language, puts() is a function defined in header <stdio.h>
that prints strings character by character until the NULL character is
encountered. The puts() function prints the newline character at the end of the
output string. Its ability to automatically add a newline at the end of the
output makes it convenient for many applications.
Syntax
:- int puts(char* str);
Parameters,
str: string to be printed. , Return Value , The return value of the puts
function depends on the success/failure of its execution. On success, the
puts() function returns a non-negative value. Otherwise, an End-Of-File (EOF)
error is returned.
EXAMPLE :-
//
C program to illutrate the use of puts() function
#include
<stdio.h>
#include<string.h>
#include<conio.h>
int
main()
{
// using puts to print hello world
char* str1 = "Hello Ajay Sir";
puts(str1);
puts("Welcome Ajay Sir");
return 0;
}
OUTPUT
Hello
Ajay Sir
Welcome
Ajay Sir
EXAMPLE 2:-
#include
<stdio.h>
#include<string.h>
#include<conio.h>
int
main() {
char message[] = "Hello, World!";
puts(message); // Prints the string and moves to the next
line
return 0;
}
OUTPUT:-
Hello, World!
EXAMPLE
3:- Using gets() and puts() in C taking value from the user
#include
<stdio.h>
int
main()
{
char name[50];
printf("Enter your name: ");
gets(name); // taking input from user
puts("You entered:");
puts(name); // displaying output
return 0;
}
EXAMPLE
4:- Using gets() and puts() in C taking value from the user
#include
<stdio.h>
int
main()
{
char address[100];
printf("Enter your address: ");
gets(address);
puts("Your address is:");
puts(address);
return 0;
}
WHAT IS FORMAT SPECIFIER?.:-
INTRODUCTION:- In C programming, format specifiers are used in input/output functions like printf() and scanf() to specify the type and format of data being read or displayed. They are represented by a percentage sign (%) followed by a character indicating the data type, such as %d for integers, %f for floating-point numbers, and %s for strings. Format specifiers ensure proper interpretation and formatting of data during input and output operations.
Format
specifiers are denoted by percent (%) marks and are followed by a letter
designating the formatted data type.
List
of C Format Specifiers:-
|
Format Specifier |
Description |
|
%c |
For character type. |
|
%d |
For signed integer type. |
|
%e or %E |
For scientific notation of floats. |
|
%f |
For float type. |
|
%g or %G |
For float type with the current
precision. |
|
%i |
signed integer |
|
%ld or %li |
Long |
|
%lf |
Double |
|
%Lf |
Long double |
|
%lu |
Unsigned int or unsigned long |
|
%lli or %lld |
Long long |
|
%llu |
Unsigned long long |
|
%o |
Octal representation |
|
%p |
Pointer |
|
%s |
String |
|
%u |
Unsigned int |
|
%x or %X |
Hexadecimal representation |
|
%n |
Prints nothing |
|
%% |
Prints % character |
EXAMPLE:-
#include<stdio.h>
#include<conio.h>
int
main()
{
// Create variables
int myNum = 15; // Integer (whole number)
float myFloatNum = 5.99; // Floating point number
char myLetter = 'D'; // Character
// Print variables
printf("%d\n", myNum);
printf("%f\n", myFloatNum);
printf("%c\n", myLetter);
return 0;
}
ESCAPE SEQUENCES:-
In
C programming, an escape sequence is a combination of characters used to
represent a character that cannot be typed directly on a keyboard.
·
Each escape sequence begins with a
backslash (\) followed by a specific character.
·
These sequences are useful for
representing special characters, formatting text, and controlling hardware
devices.
·
Some escape sequences correspond to ASCII
characters, while others do not.
·
The behavior of escape sequences can vary
depending on the compiler used to compile the code, making them an essential
tool for writing clear and effective C programs.
List Of All Escape Sequences In C:-
|
Escape Sequence |
Name/ Description |
HEX Value in ASCII |
Syntax |
|
\a |
Alert or bell: Produces an
audible alert or bell sound. |
0x07 |
printf("Hello \a World"); |
|
\b |
Backspace: Moves the cursor back
by one position. |
0x08 |
printf("Hello \b World"); |
|
\f |
Form feed: Advances the printer
to the next logical page. |
0x0C |
printf("Hello \f World"); |
|
\n |
Newline: Moves the cursor to the
beginning of the next line. |
0x0A |
printf("Hello \n World"); |
|
\r |
Carriage return: Moves the cursor
to the beginning of the current line. |
0x0D |
printf("Hello \r World"); |
|
\t |
Horizontal tab: Moves the cursor
to the next horizontal tab stop. |
0x09 |
printf("Hello \t World"); |
|
\v |
Vertical tab: Moves the cursor to
the next vertical tab stop. |
0x0B |
printf("Hello \v World"); |
|
\\ |
Backslash: Inserts a backslash
character. |
0x5C |
printf("Hello \\World"); |
|
\’ |
Single quote: Inserts a single
quote character. |
0x27 |
printf("Hello \'World"); |
|
\” |
Double quote: Inserts a double quote
character. |
0x22 |
printf("Hello
\"World"); |
|
\? |
Question mark: Inserts a question
mark character. |
0x3F |
printf("Hello \? World"); |
|
\0 |
Null character: Terminates the
string/ character literal wherever it is placed. |
0x00 |
char str[] = "Hello \0
World"; |
|
\nnn |
Octal value: Inserts the
character represented by the octal value nnn. |
0x00 to 0xFF |
printf("Hello \nnn World"); |
|
\xhh |
Hexadecimal value: Inserts the
character represented by the hexadecimal value hh. |
0x00 to 0xFF |
printf("Hello \xhh World"); |
|
\uhhhh |
Universal character name: Inserts
the character represented by the Unicode value hhhh. |
None |
printf("Hello \uhhhh
World"); |
DECISION CONTROL STRUCTURES :-
INTRODUCTION :- In a programming language, we must
perform various tasks based on the conditions available to us. For example, let
us consider an online website. Whenever someone enters the wrong password or
ID, it will display an error page, while if they enter the correct credentials,
then the website will display them a welcome page. Thus, there might be some
type of logic here that checks the available conditions (password and ID). If
the conditions return to be true, then it will perform the assigned task (in
this case, displaying the welcome page). Or else, it will perform a very
different task (in this place, displaying the error page).
When
we use the decision control statements, we get to control the flow of any
program with us in such a way that it gets to execute some statements on the
basis of an available condition’s outcome (the condition can be both true or
false).
TYPES OF DECISION CONTROL STATEMENTS IN C:-
These
are:-
1. if statement
2. switch statement
3. Conditional operator statement (? : operator)
4. Jump Statements:- Break , Continue , Return, goto statement
(1) if statements:- The
if Statement in C Language:- (IF STATEMENT IS DIVIDED IN TWO PARTS)
(A) if-else statements
(B) nested if statements
Now The if Statement in C Language :- The execution of
the statements available inside an if block will only happen when the condition
defined by this statement turns out to be true. In case the available condition
is false, the compiler will skip the available statement that gets enclosed in the
body of the if statement. One can have as many numbers of if statements in a
program (in C language) as we want.
Syntax:-
The Syntax available for the if statement will be:-
if
(condition x)
{
//
A block of statements for the C program
//
The execution of these statements will only happen when this condition turns to
be true
}
There
will be an execution of the statements available inside the body of the if
block whenever the given condition returns to be true. In case this condition
returns to be false, then the program will skip the statements that we have
inside the if block.
EXAMPLE 1:-
Let
us look at an example of a program that will ultimately print the highest
number.
#include
<stdio.h>
void
main()
{
int
x;
printf(“We
enter any number:”);
scanf(“%d”,
&x);
printf
(“The number entered here is %d”, x);
if
(x>100)
printf
(“HELLO. You have entered a comparatively higher number.”);
}
EXAMPLE 2:-
#include<stdio.h>
int
main()
{
int mynumber;
scanf("%d",&mynumber);
if (mynumber = = 10)
{
printf("Entered Number is
equal\n");
printf("closing program
!\n")
}
return 0;
}
(A) The if-else Statement
in C Language:- The if-else Statement in C Language We have two blocks of statements in the case
of this type of decision control statement- one if the available condition is
true and another one when this condition is false. When the statement available
in the if body results to be true, then the statement inside that block will
surely execute. In case it is false, then there will be an execution of the
statement inside the else block. It means that the else statement cannot exist
in a program if there is no if statement.
Syntax:-The
syntax available for the if-else statement will be:
if
(condition x)
{
//
The statements present inside the body of if
}
else
{
//
The statements present inside the body of else
}
When
the statement present in the if condition returns true, then the program will
execute the statement that is present inside the body of this block. Here, the
compiler will skip the statement that is present inside the body if the else
block. Equally, when the condition present inside the if block is false, then
the compiler will skip the block and will execute the statement present in the
else block.
EXAMPLE 1:- Let us look at an example of a program
that we use in case of a leap year.
#include
<stdio.h>
void
main()
{
int
year;
clrscr();
printf(“We
will enter a year here:”);
scanf(“%d”,
&yr);
if
((year%4 = = 0) && ((year%100 ! =0) || (year%400= =0)))
printf(“Yes.
The provided year is a leap year. Great job…!!!!”);
else
printf
(“No. The provided year is not a leap year. Try again….!!!”);
}
EXAMPLE 2:- Check entered number is equal or not
#include<stdio.h>
int
main()
{
int mynumber;
scanf("%d",&mynumber);
if ( mynumber == 10 )
{
printf("Entered Number is
equal\n");
}
else
{
printf("Entered Number is Not
equal\n");
}
return 0;
}
(B) The nested if Statement
in C Language:- ( A
nested if in C is an if statement that is the target of another if statement.
Nested if statements mean an if statement inside another if statement. Yes, C
allow us to nested if statements within if statements, i.e, we can place an if
statement inside another if statement. )
The
nested if statement is fairly useful in case a user needs to evaluate multiple
types of conditions. Here, the if block is present to define a condition (or an
expression). The resultant statement will get executed on the basis of the
result of this expression (when the condition is true or false).
Syntax:-The
syntax available for the nested if statement will be:
{
if
(condition x)
{
Statement x; }
//
The C Statement for this condition
else_if(condition
y)
//
The C Statement for this condition
{
Statement y; }
else
Statement
z;
default:
//
The C Statement for this default condition
;
}
When
the condition available in the if block is true, there will be an execution of
the provided statement. When it is false, the program will check the next
condition. If it is true, the execution of the statement associated with this
condition will occur. In case this one is also false, then there will be a
default execution of a final statement. Here, we may have as many types of
cases as possible. However, there must be just one type of default statement.
EXAMPLE:-
Let
us look at an example of a program that we use for finding out about two
variables that might be greater than or smaller than each other.
#include
<stdio.h>
int
main()
{
int
a=40,b=20;
if
(a>b) {
printf(“The
number a is greater than the number b”);
}
else
if(a<n) {
printf(“The
number a is less than the number b”);
}
else
{
printf(“The
number a is equal to the number b”);
}
}
The output generated here would be:-The number a is
greater than the number b
EXAMPLE 2:-
#include
<stdio.h>
int
main()
{
int age = 11;
if (age >= 18) {
if (age >= 60)
printf("Eligible to vote
(Senior Citizen)\n");
else
printf("Eligible for
vote\n");
}
else {
printf("Not eligible to vote
(Under 18)\n");
if (age >= 13)
printf("teenager\n");
else
printf("not a
teenager\n");
}
return 0;
}
EXAMPLE 3:- Determine Grade Based on Marks
#include
<stdio.h>
int
main() {
int marks;
printf("Enter your marks: ");
scanf("%d", &marks);
if (marks >= 50) { // Outer condition
if (marks >= 90) { // Inner condition
printf("Grade: A\n");
} else {
printf("Grade: B\n");
}
} else {
printf("Grade: F\n");
}
return 0;
}
EXAMPLE 4:- Check If a Number is Positive, Negative,
or Zero
#include
<stdio.h>
int
main()
{
int number;
printf("Enter a number: ");
scanf("%d", &number);
if (number > 0) { // Outer condition
printf("The number is
positive.\n");
} else {
// Outer else
if (number == 0) { // Inner condition
printf("The number is
zero.\n");
} else {
printf("The number is negative.\n");
}
}
return 0;
}
( C ) if-else-if Ladder in C:- The if else if
statements are used when the user has to decide among multiple options. The C
if statements are executed from the top down. As soon as one of the conditions
controlling the if is true, the statement associated with that if is executed,
and the rest of the C else-if ladder is bypassed. If none of the conditions is
true, then the final else statement will be executed. if-else-if ladder is
similar to the switch statement.
EXAMPLE:-
#include
<stdio.h>
int
main()
{
int i = 20;
// If else ladder with three conditions
if (i == 10)
printf("Not Eligible");
else if (i == 15)
printf("wait for three
years");
else if (i == 20)
printf("You can vote");
else
printf("Not a valid age");
return 0;
}
2. switch statement:- The switch case or
switch statement in C programming is a control structure used to execute one
block of code from multiple options based on the value of an expression. It
compares the expression’s value against predefined constant cases and executes
the matching block. If no match is found, the default block (if provided) is
executed. It’s ideal for handling multiple specific conditions efficiently.
The
switch statement in C is an alternate to if-else-if ladder statement which
allows us to execute multiple operations for the different possible values of a
single variable called switch variable. Here, We can define various statements
in the multiple cases for the different values of a single variable.
Syntax
of Switch Statement in C:-
switch
(expression) {
case constant1:
// Code to execute if expression
matches constant1
break;
case constant2:
// Code to execute if expression
matches constant2
break;
...
default:
// Code to execute if no case matches
}
Components
of Syntax:
|
Component |
Explanation |
|
switch (expression) |
The
expression is evaluated once and compared against the constants in each case.
It must result in an integer or character value. |
|
case constant |
Represents
a specific value to compare with the expression. Each case label must have a
unique constant value. |
|
Statements |
Code
to execute when the case matches the expression. These can include multiple
lines of code. |
|
break |
Ends
the execution of the current case and exits the switch block. Without break,
the program continues to execute subsequent cases (fall-through behavior). |
|
default |
An
optional block executed if no case matches the expression. It acts as a
catch-all for unmatched cases. |
EXAMPLE
:- Practical Example to Understand switch case syntax:
Below
is a program to print the Day of the Week using switch statement in C:
#include
<stdio.h>
int
main() {
int day;
printf("Enter a number (1-7): ");
scanf("%d", &day);
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
case 4:
printf("Thursday\n");
break;
case 5:
printf("Friday\n");
break;
case 6:
printf("Saturday\n");
break;
case 7:
printf("Sunday\n");
break;
default:
printf("Invalid day\n");
}
return 0;
}
EXAMPLE
2:- Perform Basic Arithmetic Operations
#include
<stdio.h>
int
main() {
int num1, num2, result;
char operator;
printf("Enter two numbers: ");
scanf("%d %d", &num1,
&num2);
printf("Enter an operator (+, -, *,
/): ");
scanf(" %c", &operator);
switch (operator) {
case '+':
result = num1 + num2;
printf("Result: %d\n",
result);
break;
case '-':
result = num1 - num2;
printf("Result: %d\n",
result);
break;
case '*':
result = num1 * num2;
printf("Result: %d\n",
result);
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
printf("Result:
%d\n", result);
} else {
printf("Error: Division by
zero is not allowed.\n");
}
break;
default:
printf("Invalid
operator\n");
}
return 0;
}
3. Conditional operator statement (? : operator):-
The
conditional operator ?:, also known as the
ternary conditional operator, evaluates a Boolean expression and returns the
result of one of the two expressions, depending on whether the Boolean
expression evaluates to true or false, as the following example shows:
The
conditional operator in C is kind of similar to the if-else statement as it
follows the same algorithm as of if-else statement but the conditional operator
takes less space and helps to write the if-else statements in the shortest way
possible.
Syntax
of Conditional / Ternary Operator in C:-
variable
= (condition) ? Expression2 : Expression3;
EXPLANATION:-
|
Component |
Explanation |
|
condition |
An
expression that evaluates to either true (non-zero) or false (zero). |
|
? |
Indicates the start of the ternary
operator. |
|
expression_if_true |
The value or expression executed if
the condition is true. |
|
: |
Separates the true expression from the
false expression. |
|
expression_if_false |
The value or expression executed if
the condition is false. |
EXAMPLE :- WAP IN C LANGUAGE TO FIND THE YOU ARE
ELIGIBLE FOR VOTE OR NOT
#include
<stdio.h>
int
main()
{
int age;
// take input from users
printf("Enter your age: ");
scanf("%d", &age);
//
ternary operator to find if a person can vote or not
(age >= 18) ? printf("You can
vote") : printf("You cannot vote");
return 0;
}
EXAMPLE 2:- C Program to Store the greatest of the
two Numbers using the ternary operator
//
C program to find largest among two, numbers using ternary operator
#include
<stdio.h>
int
main()
{
int m = 5, n = 4;
(m > n) ? printf("m is greater than
n that is %d > %d", m, n)
: printf("n is greater than m
that is %d > %d", n, m);
return 0;
}
EXAMPLE 3: - C
Program to check whether a year is a leap year using ternary operator
//
C program to check whether a year is leap year or not
//
using ternary operator
//
conditional operator in c with example
#include
<stdio.h>
int
main() {
int year;
printf("Enter a year: ");
scanf("%d", &year);
((year % 4 == 0 && year % 100 != 0)
|| (year % 400 == 0))
? printf("%d is a leap
year.\n", year)
: printf("%d is not a leap
year.\n", year);
return 0;
}
4. Jump Statements:-
Jump
statements are control flow statements that let you change the order in which
programs execute. These statements provide flexibility and control over program
logic to the programmer.
Jump
statements in C change the usual order in which code runs by moving the control
to another part of the program. They are essential for implementing complex
control structures, handling exceptions, and managing the flow of loops and
functions. Understanding how and when to use these statements is crucial for
writing efficient and maintainable C code
Types of Jump Statements:-
There
are mainly five keywords in the Jump Statements which are mentioned below:
(1) break
(2) continue
(3) goto
(4) return
(5) throw
(1) break:- The
break statement in C language is used to exit from a loop or switch statement,
prematurely, before the loop or switch block has been fully executed. When a
break statement is encountered inside a loop, it immediately terminates the
loop, and control is transferred to the next statement outside the loop.
Similarly, when a break statement is encountered inside a switch block, it
terminates the block, and control is transferred to the next statement outside
the block.
EXAMPLE
1:- // Use of break statement using System;
#include
<stdio.h>
int
main()
{
for (int i = 1; i <= 10; i++) {
if (i = = 5) {
break; // Terminates the loop when i is equal
to 5
}
printf("%d\n", i);
}
return 0;
}
EXAMPLE 2:- Program to perform all arithmetic
operations using switch statement.
#include<stdio.h>
#include<conio.h>
void main()
{
int number1, number2, result ;
char operator;
clrscr() ;
printf("Enter any two integer numbers:
") ;
scanf("%d%d", &number1,
&number2) ;
printf("Please enter any arithmetic
operator: ");
operator = getchar();
switch(operator)
{
case '+': result = number1 + number2 ;
printf("Addition =
%d", result) ;
break;
case '-': result = number1 - number2 ;
printf("Subtraction =
%d", result) ;
break;
case '*': result = number1 * number2 ;
printf("Multiplication =
%d", result) ;
break;
case '/': result = number1 / number2 ;
printf("Division =
%d", result) ;
break;
case '%': result = number1 % number2 ;
printf("Remainder =
%d", result) ;
break;
default: printf("\nWrong
selection!!!") ;
}
getch() ;
}
(2) continue:-
The continue statement is used to move the program execution control to the
beginning of the looping statement. When the continue statement is encountered
in a looping statement, the execution control skips the rest of the statements
in the looping block and directly jumps to the beginning of the loop. The
continue statement can be used with looping statements like while, do-while and
for.
When
we use continue statement with while and do-while statements the execution
control directly jumps to the condition. When we use continue statement with
for statement the execution control directly jumps to the modification portion
(increment/decrement/any modification) of the for loop.
Example:- Program to illustrate continue statement.
#include<stdio.h>
#include<conio.h>
void
main()
{
int number ;
clrscr() ;
while (
1 )
{
printf("Enter any integer number:
") ;
scanf("%d", &number) ;
if(number %2 = = 0)
{
printf("Entered number is
EVEN!!! Try another number!!!\n") ;
continue ;
}
else
{
printf("You have entered ODD
number!!! Bye!!!") ;
exit(0) ;
}
}
getch() ;
}
EXAMPLE 2: - CHECK EVEN OR ODD NUMBER
#include
<stdio.h>
int
main() {
int i;
for (d = 1; d <= 10; d++) {
if (d % 2 == 0) {
continue; // Skip even numbers
}
printf("%d\n", d);
}
return 0;
}
EXAMPLE 3: - Using continue in While Loops (even number or odd
number)
#include
<stdio.h>
int
main() {
int i = 0;
while (i < 10) {
i++;
if (i % 2 == 0) {
continue; // Skip even numbers
}
printf("%d\n", i);
}
return 0;
}
EXAMPLE 3: - Using continue
in Do-While Loops (EVEN NUMBER OR ODD NUMBER)
#include
<stdio.h>
int
main() {
int i = 0;
do {
i++;
if (i % 2 == 0) {
continue; // Skip even numbers
}
printf("%d\n", i);
} while (i < 10);
return 0;
}
(3) goto Statement:- The goto statement is
one of the jump statements in C that transfers control unconditionally to a labeled
statement within the same function. Unlike structured control flow mechanisms
(like loops and conditional statements), the goto Jump statement in C allows
the program to jump to an arbitrary point, making the code less readable and
more complex to debug. However, it can be helpful in specific scenarios, such
as error handling in deeply nested loops.
Goto
Statement in C Syntax
label_name:
// Statements
//
Somewhere else in the function
goto
label_name;
EXAMPLE 1: - PRINT 1 TO 3
#include
<stdio.h>
int
main() {
for (int l = 1; l <= 3; l++) {
for (int m = 1; m <= 3; m++) {
printf("l=%d, m=%d\n", l,
m);
if (l = = 2 && m = = 2) {
goto exit_loop; // Break out of
both loops
}
}
}
exit_loop: // Label to jump to
printf("Exited the loop\n");
return 0;
}
EXAMPLE:- USE GOTO
#include
<stdio.h>
int
main() {
int num = 1;
start: // Label
printf("%d\n", num);
num++;
if (num <= 5) {
goto start; // Jump back to 'start'
label
}
return 0;
}
(4) return:- To
terminate a function and also return a value to the caller function, use the
return statement. It plays a crucial role in determining the flow of execution
in a program, allowing functions to send results back to their callers and
terminate execution early when necessary.
Syntax
of Return Statement
The
syntax of return depends on whether the function returns a value or not :-
return
expression;
EXAMPLE 1: -
#include
<stdio.h>
int
add(int a, int b)
{
int sum = a + b;
// Return the sum as the result of the
// function
return sum;
}
void
printMessage()
{
// Return from the function with no value
(void)
printf("C CLASS BY AJAY \n");
return;
}
int
main()
{
int result = add(5, 3);
printf("Result: %d\n", result);
printMessage();
return 0;
}
EXAMPLE 2 :- CALCULATE MULTIPLICATION OF TWO NUMBERS
#include
<stdio.h>
int
multiply(int a, int b) {
return a * b;
}
int
main() {
int result = multiply(5, 7);
printf("The product is: %d\n",
result);
return 0;
}
EXAMPLE 3:- Program: Return Statement (Value Taken from User)
#include
<stdio.h>
//
function declaration
int
add(int a, int b);
int
main()
{
int x, y, result;
// taking input from user
printf("Enter first number: ");
scanf("%d", &x);
printf("Enter second number: ");
scanf("%d", &y);
// function call
result = add(x, y);
// printing result
printf("Sum = %d", result);
return 0;
}
//
function definition
int
add(int a, int b)
{
int sum;
sum = a + b;
return sum; // return statement
}
EXAMPLE 4: RETURN STATEMENT WITHOUT VALUE
#Used
when function does not return any value
#include
<stdio.h>
void
display();
int
main()
{
display();
return 0;
}
void
display()
{
printf("Hello, Welcome to C
Programming!");
return;
// no value returned
}
Advantages of Jump Statements in C:-
1.
Simplified
Loop Control:- Jump statements
like break and continue allow for easier and more efficient control of loops,
providing a way to exit or skip iterations without complex conditions.
2.
Error
Handling:- By quickly jumping
to error-handling code, the goto statement helps minimize code duplication and
facilitate the management of error answers.
3.
Increased
Efficiency:- With jump
statements, unnecessary computations can be skipped, improving the efficiency
of code execution, especially in complex loops or conditional structures.
4.
Code
Simplification:- In some cases, jump
statements reduce the need for extra flags or nested conditions, making the
code more straightforward and easier to follow.
5.
Enhanced
Flexibility:- They offer greater
control over the flow of the program, allowing developers to jump to specific
points based on dynamic conditions.
Disadvantages of Jump Statements in C
1.
Reduced
Readability:- Overuse of jump
statements, particularly goto, can make the program flow hard to follow,
leading to confusing and unreadable code.
2.
Increased
Complexity:- Excessive use of jump
statements may lead to tangled code with multiple entry and exit points, making
debugging and maintenance more difficult.
3.
Potential
for Errors:- Jumping between code
sections can result in unpredictable behavior, especially in complex programs,
leading to potential logical errors.
4.
Poor
Maintainability:- Code with many jump
statements may become harder to maintain, as changes in one part of the code
can impact the flow of control in unexpected ways.
5.
Difficult
Debugging: Debugging becomes
challenging with jump statements, particularly goto, as it may lead to control
flow that is hard to track and manage during execution.
THE END UNIT 3 OF NUMERICAL ANALYSIS AND C PROGRAMMING

No comments:
Post a Comment
PLEASE DO LEAVE YOUR COMMENTS